package com.atguigu.atcrowdfunding.interceptor;

import com.atguigu.atcrowdfunding.bean.Permission;
import com.atguigu.atcrowdfunding.manager.service.PermissionService;
import com.atguigu.atcrowdfunding.manager.service.UserService;
import com.atguigu.atcrowdfunding.util.Const;
import com.atguigu.atcrowdfunding.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author xzt
 * @create 2021-02-28 10:37
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private PermissionService permissionService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String servletPath = request.getServletPath();

        //获取系统所有许可权限菜单，请求路径必须包含于许可菜单中，否则拒绝访问

        //如果每次拦截请求都查询数据库表的所有许可，效率比较低
        /*List<Permission> allPermission = permissionService.queryAllPermission();
        Set<String> allPermissionUrls = new HashSet<>();

        for (Permission permission : allPermission) {
            if(StringUtil.isNotEmpty(permission.getUrl())){
                allPermissionUrls.add("/"+permission.getUrl());
            }
        }*/

        //改进：在服务器启动时加载所有许可路径。并存放到application域中
        Set<String> allPermissionUrls = (Set<String>)request.getSession().getServletContext().getAttribute(Const.ALL_PERMISSION_URI);

        if(allPermissionUrls.contains(servletPath)){

            //判断请求路径是否在用户所拥有的权限内
            Set<String> myURIs = (Set<String>) request.getSession().getAttribute(Const.MY_URIS);
            if(myURIs.contains(servletPath)){
                return true;
            }else{
                response.sendRedirect(request.getContextPath()+"/login.htm");
                return false;
            }

        }else{
            return true;
        }

    }
}
